//
//  ActiveSignalMapViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 5/31/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "ActiveSignalMapViewController.h"

@interface ActiveSignalMapViewController ()

@end

@implementation ActiveSignalMapViewController
@synthesize mapView;
@synthesize signalNameLabel;
@synthesize countDownLabel;
@synthesize currentPhaseLabel;
@synthesize nextPhaseLabel;
@synthesize countDownLabel2 = _countDownLabel2;
@synthesize currentPhaseLabel2 = _currentPhaseLabel2;
@synthesize nextPhaseLabel2 = _nextPhaseLabel2;
@synthesize GPSDescriptionLabel = _GPSDescriptionLabel;
@synthesize agency=_agency;
@synthesize subSystem=_subSystem;
@synthesize timingPattern=_timingPattern;
@synthesize signalList=_signalList;
@synthesize currentSignal=_currentSignal;
@synthesize timer=_timer;
@synthesize geometryCalculation=_geometryCalculation;
@synthesize heading=_heading;
@synthesize offsetPhaseTime=_offsetPhaseTime;
@synthesize logFilePath=_logFilePath;
@synthesize recordGPS=_recordGPS;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.currentSignal=nil;
    if (!_geometryCalculation) {
        _geometryCalculation=[[GeometryCalculation alloc] init];
    }
    
    allowHeading=NO;
//    [ buttonItem release ];
        UIBarButtonItem *buttonItem1 = [[[ UIBarButtonItem alloc ] initWithTitle: @"Back"
                                                        style: UIBarButtonItemStyleBordered
                                                       target: self
                                                       action: @selector( goBack:) ] autorelease];
//        self.toolbarItems = [ NSArray arrayWithObject: buttonItem1 ];
    //    [ buttonItem release ];
    MKUserTrackingBarButtonItem *buttonItem = [[[MKUserTrackingBarButtonItem alloc] initWithMapView:self.mapView] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    UIBarButtonItem *typeButton = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemPageCurl target:self action:@selector(changeMapType:)] autorelease];
//    UIBarButtonItem *recordGPSButton = [[[ UIBarButtonItem alloc ] initWithTitle: @"Record GPS"
//                                                                           style: UIBarButtonItemStyleBordered
//                                                                          target: self
//                                                                          action: @selector( clickRecordGPSButton:) ] autorelease];;
//    recordGPSButton.tintColor=[UIColor redColor];
    
    //    [typeButton set]
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    
    self.toolbarItems = [ NSArray arrayWithObjects:homeButtonItem,space, buttonItem1, buttonItem,typeButton,nil];
    //[ buttonItem release ];
    //    UIBarButtonItem *butstonItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Back"
    //                                                    style: UIBarButtonItemStyleBordered
    //                                                   target: self
    //                                                   action: @selector( goBack:) ];
    //    self.toolbarItems = [ NSArray arrayWithObject: buttonItem ];
    //    [ buttonItem release ];
    
    
    self.mapView.delegate = self;     
    locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locationManager startUpdatingLocation];
    [locationManager startUpdatingHeading];
    [self.mapView setShowsUserLocation:YES];
    
    self.recordGPS=NO;
//    self.signalNameLabel.text=@"No signal detected";
    
    //Logfile path
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    NSDate *time=[NSDate date];
    
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyymmdd-HH-mm-ss"];
    NSString *stringFromDate = [formatter stringFromDate:time];
    self.logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@.gps",documentsDir,stringFromDate] autorelease];
    
    
    
    if (!_signalList) {
        self.signalList=[XMLParser getSignalList:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }
    MKCoordinateRegion region;
    CLLocationCoordinate2D c={0,0};
    region.center=c;
    for (Signal *signal in self.signalList) {
        Intersection *intersection=[XMLParser getIntersection:signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        if (intersection.intersectionCoordinate.latitude!=0) {
            region = MKCoordinateRegionMakeWithDistance(intersection.intersectionCoordinate ,5000,5000);
            break;
        }
    }
    
    
    //    = MKCoordinateRegionMakeWithDistance(self.currentSignal.coordinate ,5000,5000);
    if (region.center.latitude==0) {
        region=[PropertyReadingWritingClass readMapRegionFromPropertyFile];
    }
    
    if (region.center.latitude==0) {
        region = MKCoordinateRegionMakeWithDistance(locationManager.location.coordinate ,5000,5000);
    }
    [self.mapView setRegion:region animated:YES];
//    [self.mapView setShowsUserLocation:NO];
    for ( int i=0;i<self.signalList.count;i++) {
        Signal *signal=[self.signalList objectAtIndex:i];
        //        CLLocationCoordinate2D newCoord = region.center;
        Intersection *intersection=[XMLParser getIntersection:signal.signalID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
        if (intersection.intersectionCoordinate.latitude!=0) {
            MapPoint *mp = [[[MapPoint alloc] initWithCoordinate:intersection.intersectionCoordinate title:signal.signalName subTitle:@""] autorelease];
            mp.tag=i;
            
            
            [self.mapView addAnnotation:mp];
        }
        
        
    }
    
    
    
    // Do any additional setup after loading the view from its nib.
    
    
    {
        self.currentSignal=[self.geometryCalculation calculateNextSignal:self.signalList newHeading:self.heading  coordinate:locationManager.location.coordinate agency:self.agency subSystem:self.subSystem];
        if (!self.currentSignal) {
            return;
        }
        
        {
            self.offsetPhaseTime=0;
            int i=0;
            for (i=0; i<self.currentSignal.ring1.phaseList.count; i++) {
                SignalPhase *phase=[self.currentSignal.ring1.phaseList objectAtIndex:i];
                if ([self.currentSignal.offsetPhase isEqualToString:phase.phaseID]) {
                    if ([self.currentSignal.offsetBorE isEqualToString:@"Green End"]) {
                        self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue];
                        
                    }
                    break;
                }
                self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
            }
            if (i>=self.currentSignal.ring1.phaseList.count) {
                self.offsetPhaseTime=0;
                for (i=0; i<self.currentSignal.ring2.phaseList.count; i++) {
                    SignalPhase *phase=[self.currentSignal.ring2.phaseList objectAtIndex:i];
                    if ([self.currentSignal.offsetPhase isEqualToString:phase.phaseID]) {
                        if ([self.currentSignal.offsetBorE isEqualToString:@"Green End"]) {
                            self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue];
                            
                        }
                        break;
                    }
                    self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
                }
                if (i>=self.currentSignal.ring2.phaseList.count) {
                    self.offsetPhaseTime=0;
                }
            }
        }
        int controllerTimer=[TrafficSignalTimer calculateCycleTimer:[self.currentSignal.cycleLength intValue] offSet:([self.currentSignal.offset intValue]-self.offsetPhaseTime) syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
        int cycleTimer=controllerTimer;
        for (int i=0; i<self.currentSignal.ring1.phaseList.count; i++) {
            SignalPhase *phase=[self.currentSignal.ring1.phaseList objectAtIndex:i];
            
            if (cycleTimer<[phase.greenTime doubleValue]) {
                self.countDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
                self.countDownLabel.textColor=[UIColor greenColor];
                self.currentPhaseLabel.text=phase.phaseMovement;
                
                if (i==self.currentSignal.ring1.phaseList.count-1) {
                    SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:0];
                    self.nextPhaseLabel.text=nextPhase.phaseMovement;
                }else {
                    SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:i+1];
                    self.nextPhaseLabel.text=nextPhase.phaseMovement;
                }
                
                break;
            }
            if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
                
                self.countDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
                self.countDownLabel.textColor=[UIColor yellowColor];
                self.currentPhaseLabel.text=phase.phaseMovement;
                
                if (i==self.currentSignal.ring1.phaseList.count-1) {
                    SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:0];
                    self.nextPhaseLabel.text=nextPhase.phaseMovement;
                }else {
                    SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:i+1];
                    self.nextPhaseLabel.text=nextPhase.phaseMovement;
                }
                break;
            }
            if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
                self.countDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
                self.countDownLabel.textColor=[UIColor redColor];
                self.currentPhaseLabel.text=phase.phaseMovement;
                
                if (i==self.currentSignal.ring1.phaseList.count-1) {
                    SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:0];
                    self.nextPhaseLabel.text=nextPhase.phaseMovement;
                }else {
                    SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:i+1];
                    self.nextPhaseLabel.text=nextPhase.phaseMovement;
                }
                break;
            }
            cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
            //            self.Ring1CurrentPhaseLabel.text=[NSString stringWithFormat:@"NO Phase"];
        }
        
        
        cycleTimer=controllerTimer;
        for (int i=0; i<self.currentSignal.ring2.phaseList.count; i++) {
            SignalPhase *phase=[self.currentSignal.ring2.phaseList objectAtIndex:i];
            
            if (cycleTimer<[phase.greenTime doubleValue]) {
                self.countDownLabel2.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
                self.countDownLabel2.textColor=[UIColor greenColor];
                self.currentPhaseLabel2.text=phase.phaseMovement;
                
                if (i==self.currentSignal.ring2.phaseList.count-1) {
                    SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:0];
                    self.nextPhaseLabel2.text=nextPhase.phaseMovement;
                }else {
                    SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:i+1];
                    self.nextPhaseLabel2.text=nextPhase.phaseMovement;
                }
                
                break;
            }
            if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
                
                self.countDownLabel2.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
                self.countDownLabel2.textColor=[UIColor yellowColor];
                self.currentPhaseLabel2.text=phase.phaseMovement;
                
                if (i==self.currentSignal.ring2.phaseList.count-1) {
                    SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:0];
                    self.nextPhaseLabel2.text=nextPhase.phaseMovement;
                }else {
                    SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:i+1];
                    self.nextPhaseLabel2.text=nextPhase.phaseMovement;
                }
                break;
            }
            if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
                self.countDownLabel2.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
                self.countDownLabel2.textColor=[UIColor redColor];
                self.currentPhaseLabel2.text=phase.phaseMovement;
                
                if (i==self.currentSignal.ring2.phaseList.count-1) {
                    SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:0];
                    self.nextPhaseLabel2.text=nextPhase.phaseMovement;
                }else {
                    SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:i+1];
                    self.nextPhaseLabel2.text=nextPhase.phaseMovement;
                }
                break;
            }
            cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
            //            self.Ring1CurrentPhaseLabel.text=[NSString stringWithFormat:@"NO Phase"];
        }
    }
    
    
}

- (void)viewDidUnload
{
    [self setMapView:nil];
    [self setCountDownLabel2:nil];
    [self setCurrentPhaseLabel2:nil];
    [self setNextPhaseLabel2:nil];
    [self setGPSDescriptionLabel:nil];
    [super viewDidUnload];
    self.agency=nil;
    self.subSystem=nil;
    self.timingPattern=nil;
    self.signalList=nil;
    self.currentSignal=nil;
    self.timer=nil;
    self.geometryCalculation=nil;
//    [self setMapView:nil];
//    [self setMapView:nil];
    [self setSignalNameLabel:nil];
    [self setCountDownLabel:nil];
    [self setCurrentPhaseLabel:nil];
    [self setNextPhaseLabel:nil];
    self.logFilePath=nil;
    
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    if (!self.currentSignal) {
//        return;
//    }
//    if (self.currentSignal.cycleLength==0) {
//        return;
//    }
    self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setToolbarHidden:NO];
    [self.navigationController setNavigationBarHidden:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [PropertyReadingWritingClass writeMapRegionToPropertyFile:mapView.region];
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController setToolbarHidden:YES];
    [self.timer invalidate];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) goBack:(id)sender
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) clickRecordGPSButton:(id)sender
{
    if (self.recordGPS) {
        self.recordGPS=NO;
        UIBarButtonItem *button=(UIBarButtonItem *)sender;
        button.title=@"Record GPS";
        button.tintColor=nil;
        
        //Logfile path
        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDir = [documentPaths objectAtIndex:0];
        NSDate *time=[NSDate date];
        
        NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
        [formatter setDateFormat:@"yyyymmdd-HH-mm-ss"];
        NSString *stringFromDate = [formatter stringFromDate:time];
        self.logFilePath = [[[NSString alloc] initWithFormat:@"%@/%@.gps",documentsDir,stringFromDate] autorelease];
    }else {
        self.recordGPS=YES;
        UIBarButtonItem *button=(UIBarButtonItem *)sender;
        button.title=@"Stop";
        button.tintColor=[UIColor redColor];
    }
    
}

- (void)dealloc {
    [mapView release];
    [_agency release];
    [_subSystem release];
    [_timingPattern release];
    [_signalList release];
    [_currentSignal release];
    [_timer release];
    [_geometryCalculation release];
//    [mapView release];
//    [mapView release];
    [signalNameLabel release];
    [countDownLabel release];
    [currentPhaseLabel release];
    [nextPhaseLabel release];
    
    [_countDownLabel2 release];
    [_currentPhaseLabel2 release];
    [_nextPhaseLabel2 release];
    [_GPSDescriptionLabel release];
    [_logFilePath release];
    [super dealloc];
//    [super dealloc];
}

- (void)mapView:(MKMapView *)theMapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    //    [theMapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
//    CLLocationCoordinate2D userCoordinate = userLocation.location.coordinate;
    //    for(int i = 1; i<=5;i++)
    //    {
    //        CGFloat latDelta = rand()*.035/RAND_MAX -.02;
    //        CGFloat longDelta = rand()*.03/RAND_MAX -.015;
    //        CLLocationCoordinate2D newCoord = { userCoordinate.latitude + latDelta, userCoordinate.longitude + longDelta };
    //        MapPoint *mp = [[MapPoint alloc] initWithCoordinate:newCoord title:[NSString stringWithFormat:@"Azam Home %d",i] subTitle:@"Home Sweet Home"];    
    //        [theMapView addAnnotation:mp];
    //        [mp release];
    //
    //    }
    
}

- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{    
    CGRect visibleRect = [mapView annotationVisibleRect];
    
    for(MKAnnotationView *view in views)
    {
        if([view isKindOfClass:[SignalAnnotationView class]])
        {
            CGRect endFrame = view.frame;
            CGRect startFrame = endFrame;
            startFrame.origin.y = visibleRect.origin.y - startFrame.size.height;
            view.frame = startFrame;
            //            [UIView beginAnimations:@"drop" context:NULL];
            //            [UIView setAnimationDuration:0.5];
            view.frame = endFrame;
            [UIView commitAnimations];
        }
    }
    //    MKAnnotationView *annotationView = [views objectAtIndex:0];
    //    id<MKAnnotation> mp = [annotationView annotation];
    //    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,5000,5000);
    //    MKCoordinateRegion region=[PropertyReadingWritingClass readMapRegionFromPropertyFile];
    //    if (region.center.latitude==0) {
    //        region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,5000,5000);
    //    }
    //    [mv setRegion:region animated:YES];
    
}

- (MKAnnotationView *)mapView:(MKMapView *)mv viewForAnnotation:(id <MKAnnotation>)annotation
{
    //    NSLog(@"%@",ann)
    if([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    NSString *annotationIdentifier = @"SignalViewAnnotation";
    //    SignalAnnotationView *pinView = (SignalAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
    //    if (!pinView)
    //    {
    SignalAnnotationView *pinView = [[[SignalAnnotationView alloc]                     initWithAnnotation:annotation 
                                                                                          reuseIdentifier:annotationIdentifier] autorelease];
    
    //        [pinView setPinColor:MKPinAnnotationColorGreen];
    //        pinView.animatesDrop = YES;
    pinView.canShowCallout = YES;
    UIImageView *houseIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"green_signal.png"]];
    [houseIconView setFrame:CGRectMake(0, 0, 15, 30)];
    pinView.leftCalloutAccessoryView = houseIconView;
    UIButton *detailButton=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//    int testtag=[(MapPoint *)annotation tag];
    detailButton.tag=[(MapPoint *)annotation tag];
    pinView.rightCalloutAccessoryView=detailButton;
    [houseIconView release];        
    //    }
    //    else
    //    {
    //        pinView.annotation = annotation;
    //    }
    pinView.draggable=NO;
    return pinView;
}

- (void)mapView:(MKMapView *)mapView 
 annotationView:(MKAnnotationView *)annotationView 
didChangeDragState:(MKAnnotationViewDragState)newState 
   fromOldState:(MKAnnotationViewDragState)oldState 
{
    if (newState == MKAnnotationViewDragStateEnding)
    {
        CLLocationCoordinate2D droppedAt = annotationView.annotation.coordinate;
        NSLog(@"dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);
    }
}

- (void) locationManager:(CLLocationManager *)manager
        didUpdateHeading:(CLHeading *)newHeading
{
    float heading = newHeading.magneticHeading; //in degrees
    self.heading=heading;
    
//    float headingDegrees = (heading*M_PI/180); //assuming needle points to top of iphone. convert to radians
//    self.mapView.transform = CGAffineTransformMakeRotation(headingDegrees);
}

//- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
//{
//    NSLog(@"Map was moved to %f,%f\n", mapView.region.center.latitude, mapView.region.center.longitude);
//}
- (id)initWithNibNameAndTimingPattern:(NSString *)nibNameOrNil timingPattern:(TimingPattern*)timingPattern agency:(Agency*)agency subSystem:(SubSystem*)subSystem  bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    self.agency=agency;
    self.subSystem=subSystem;
    self.timingPattern=timingPattern;
    return self;
}
- (void) changeMapType: (id)sender
{
    if (mapView.mapType == MKMapTypeStandard)
        mapView.mapType = MKMapTypeSatellite;
    else
        mapView.mapType = MKMapTypeStandard;
} 
- (void)mapView:(MKMapView *)eMapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    //    NSLog(@"%@",control.class);
    NSLog(@"%d",control.tag);
    SignalDetailViewController *detailViewController=[[[SignalDetailViewController alloc] initWithNibNameAndSignal:@"SignalDetailViewController" agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signalList:self.signalList signalIndex:control.tag automaticPlayOrNot:NO bundle:nil] autorelease];
    [detailViewController setTitle:@"Signal Detail"];
    [self.navigationController pushViewController:detailViewController animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

- (void) updateTimer:(id) sender {
    self.currentSignal=[self.geometryCalculation calculateNextSignal:self.signalList newHeading:self.heading coordinate:locationManager.location.coordinate agency:self.agency subSystem:self.subSystem];
    if (!self.currentSignal) {
         self.signalNameLabel.text=@"No signal detected";
        self.countDownLabel.text=@"";
        self.countDownLabel2.text=@"";
        for (UIView *view in self.currentPhaseLabel.subviews) {
            [view removeFromSuperview];
        }
        for (UIView *view in self.currentPhaseLabel2.subviews) {
            [view removeFromSuperview];
        }
        return;
    }
    self.signalNameLabel.text=self.currentSignal.signalName;
    
    {
        self.offsetPhaseTime=0;
        int i=0;
        for (i=0; i<self.currentSignal.ring1.phaseList.count; i++) {
            SignalPhase *phase=[self.currentSignal.ring1.phaseList objectAtIndex:i];
            if ([self.currentSignal.offsetPhase isEqualToString:phase.phaseID]) {
                if ([self.currentSignal.offsetBorE isEqualToString:@"Green End"]) {
                    self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue];
                    
                }
                break;
            }
            self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
        }
        if (i>=self.currentSignal.ring1.phaseList.count) {
            self.offsetPhaseTime=0;
            for (i=0; i<self.currentSignal.ring2.phaseList.count; i++) {
                SignalPhase *phase=[self.currentSignal.ring2.phaseList objectAtIndex:i];
                if ([self.currentSignal.offsetPhase isEqualToString:phase.phaseID]) {
                    if ([self.currentSignal.offsetBorE isEqualToString:@"Green End"]) {
                        self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue];
                        
                    }
                    break;
                }
                self.offsetPhaseTime=self.offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
            }
            if (i>=self.currentSignal.ring2.phaseList.count) {
                self.offsetPhaseTime=0;
            }
        }
    }
    int controllerTimer=[TrafficSignalTimer calculateCycleTimer:[self.currentSignal.cycleLength intValue] offSet:([self.currentSignal.offset intValue]-self.offsetPhaseTime) syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
    int cycleTimer=controllerTimer;
    SignalMovementImageManager *signalMovementImageManager=[[[SignalMovementImageManager alloc] init] autorelease];
    for (int i=0; i<self.currentSignal.ring1.phaseList.count; i++) {
        SignalPhase *phase=[self.currentSignal.ring1.phaseList objectAtIndex:i];
        
        if (cycleTimer<[phase.greenTime doubleValue]) {
            self.countDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            self.countDownLabel.textColor=[UIColor greenColor];
//            self.currentPhaseLabel.text=phase.phaseMovement;
            NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:phase];
//            for (UIView *view in self.currentPhaseLabel.subviews) {
//                [view removeFromSuperview];
//            }
            for (MovementImageView *imageView in imageViewList) {
                [self.currentPhaseLabel addSubview:imageView];
            }
            
//            if (i==self.currentSignal.ring1.phaseList.count-1) {
//                SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:0];
////                self.nextPhaseLabel.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel addSubview:imageView];
//                }
//            }else {
//                SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:i+1];
////                self.nextPhaseLabel.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel addSubview:imageView];
//                }
//            }
            
            break;
        }
        if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
            
            self.countDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            self.countDownLabel.textColor=[UIColor yellowColor];
//            self.currentPhaseLabel.text=phase.phaseMovement;
            NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:phase];
//            for (UIView *view in self.currentPhaseLabel.subviews) {
//                [view removeFromSuperview];
//            }
            for (MovementImageView *imageView in imageViewList) {
                [self.currentPhaseLabel addSubview:imageView];
            }
            
//            if (i==self.currentSignal.ring1.phaseList.count-1) {
//                SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:0];
////                self.nextPhaseLabel.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel addSubview:imageView];
//                }
//            }else {
//                SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:i+1];
////                self.nextPhaseLabel.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel addSubview:imageView];
//                }
//            }
            break;
        }
        if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
            self.countDownLabel.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            self.countDownLabel.textColor=[UIColor redColor];
//            self.currentPhaseLabel.text=phase.phaseMovement;
            NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:phase];
//            for (UIView *view in self.currentPhaseLabel.subviews) {
//                [view removeFromSuperview];
//            }
            for (MovementImageView *imageView in imageViewList) {
                [self.currentPhaseLabel addSubview:imageView];
            }
            
//            if (i==self.currentSignal.ring1.phaseList.count-1) {
//                SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:0];
////                self.nextPhaseLabel.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel addSubview:imageView];
//                }
//            }else {
//                SignalPhase *nextPhase=[self.currentSignal.ring1.phaseList objectAtIndex:i+1];
////                self.nextPhaseLabel.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel addSubview:imageView];
//                }
//            }
            break;
        }
        cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
        
        //            self.Ring1CurrentPhaseLabel.text=[NSString stringWithFormat:@"NO Phase"];
    }
    
    
    cycleTimer=controllerTimer;
    for (int i=0; i<self.currentSignal.ring2.phaseList.count; i++) {
        SignalPhase *phase=[self.currentSignal.ring2.phaseList objectAtIndex:i];
        
        if (cycleTimer<[phase.greenTime doubleValue]) {
            self.countDownLabel2.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            self.countDownLabel2.textColor=[UIColor greenColor];
//            self.currentPhaseLabel2.text=phase.phaseMovement;
            NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:phase];
//            for (UIView *view in self.currentPhaseLabel2.subviews) {
//                [view removeFromSuperview];
//            }
            for (MovementImageView *imageView in imageViewList) {
                [self.currentPhaseLabel2 addSubview:imageView];
            }
            
//            if (i==self.currentSignal.ring2.phaseList.count-1) {
//                SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:0];
////                self.nextPhaseLabel2.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel2.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel2 addSubview:imageView];
//                }
//            }else {
//                SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:i+1];
////                self.nextPhaseLabel2.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel2.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel2 addSubview:imageView];
//                }
//            }
            
            break;
        }
        if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]) {
            
            self.countDownLabel2.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            self.countDownLabel2.textColor=[UIColor yellowColor];
//            self.currentPhaseLabel2.text=phase.phaseMovement;
            NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:phase];
//            for (UIView *view in self.currentPhaseLabel2.subviews) {
//                [view removeFromSuperview];
//            }
            for (MovementImageView *imageView in imageViewList) {
                [self.currentPhaseLabel2 addSubview:imageView];
            }
            
//            if (i==self.currentSignal.ring2.phaseList.count-1) {
//                SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:0];
////                self.nextPhaseLabel2.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel2.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel2 addSubview:imageView];
//                }
//            }else {
//                SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:i+1];
////                self.nextPhaseLabel2.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel2.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel2 addSubview:imageView];
//                }
//            }
            break;
        }
        if (cycleTimer<[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
            self.countDownLabel2.text=[NSString stringWithFormat:@"%.f",([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer];
            self.countDownLabel2.textColor=[UIColor redColor];
//            self.currentPhaseLabel2.text=phase.phaseMovement;
            NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:phase];
//            for (UIView *view in self.currentPhaseLabel2.subviews) {
//                [view removeFromSuperview];
//            }
            for (MovementImageView *imageView in imageViewList) {
                [self.currentPhaseLabel2 addSubview:imageView];
            }
            
//            if (i==self.currentSignal.ring2.phaseList.count-1) {
//                SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:0];
////                self.nextPhaseLabel2.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel2.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel2 addSubview:imageView];
//                }
//            }else {
//                SignalPhase *nextPhase=[self.currentSignal.ring2.phaseList objectAtIndex:i+1];
////                self.nextPhaseLabel2.text=nextPhase.phaseMovement;
//                NSArray *imageViewList=[signalMovementImageManager getMovementImageViewsOfPhase:nextPhase];
//                for (UIView *view in self.nextPhaseLabel2.subviews) {
//                    [view removeFromSuperview];
//                }
//                for (MovementImageView *imageView in imageViewList) {
//                    [self.nextPhaseLabel2 addSubview:imageView];
//                }
//            }
            break;
        }
        cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
        
        
        //            self.Ring1CurrentPhaseLabel.text=[NSString stringWithFormat:@"NO Phase"];
    }
  
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	
	CLLocationDirection direction=newLocation.course; 
    if (direction!=-1) {
        direction=direction*180/M_PI;
    }
    
   
//    self.heading=direction;
    self.GPSDescriptionLabel.text=[newLocation.description stringByAppendingFormat:@" mageticHeading:%f,courseDirection:%f",locationManager.heading.magneticHeading,direction];
    
    if (!self.recordGPS) {
        return;
    }
//    NSString *myString; //Assuume the string you want to write is this
    
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:self.logFilePath];
    if (!fileHandler) {
        NSString *content=[NSString stringWithFormat:@"GPS logs from iphone beginning at the time of \n"];
        NSData* data=[content dataUsingEncoding:NSUTF8StringEncoding];
        [data writeToFile:self.logFilePath atomically:YES ];
        fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:self.logFilePath];
    }
    [fileHandler seekToEndOfFile];
    [fileHandler writeData:[[NSString stringWithFormat:@"%@\n",newLocation.description] dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandler closeFile];
}
- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
@end

